#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import multiprocessing
import sys
import time
from subprocess import Popen

import pickledb
import rx
from rx import operators as ops
from rx.scheduler import ThreadPoolScheduler
from selenium import webdriver

from module import login
from module import obj2str
from module import robot

if __name__ == '__main__':
    '''初始化信息'''
    proxyName = 'mitmproxyV1.py'
    #roomId = '26744536'  #懿懿
    roomId = '123579969' #测试用   # 注意测试时 注释了  send 方法的调用！只做输出
    print('开始执行__init__')
    print('程序开始初始化...')
    # 加载数据库
    print('开始加载本地db...')
    date = datetime.datetime.now().strftime('%Y-%m-%d')
    key = 'ws%s' % date
    unkey = 'unDeal%s' % date
    db = pickledb.load('ws.db', False)
    #db.dump() # 生成一下文件，防止问题。
    print('初始化数据')
    if not db.exists(key):
        list_ = db.lcreate(key)  # 创建 ws _ list
    if not db.exists(key):
        list2 = db.lcreate(unkey)  # 创建 undeal  list
    print('序列化db句柄到本地文件')
    if not obj2str.pickle_dumps_to_str(db):
        print('序列化到本地失败！')
        sys.exit(1)
    # db_str = obj2str.cutText(obj2str.pickle_dumps_to_str(db),20)

    print('执行代理程序')
    try:
        command = 'mitmdump -s {} {}'.format(proxyName,key)
        print('启动命令：' ,command)
        process = Popen(command)
    except Exception as e:
        print('启动代理失败!请检查代理脚本路径是否在当前启动程序目录下！')
        input("按任意键结束程序\n")
        print(e)
        sys.exit(1)  # 1表示异常退出， 0 正常退出

    print('执行代理成功')
    print('初始化webdriver')
    time.sleep(3) # 等待代理执行。
    option = webdriver.ChromeOptions()
    option.add_experimental_option('excludeSwitches', ['enable-automation'])
    # option.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}) #不显示图片
    option.add_argument('disable-infobars')  # 浏览器不显示受自动测试软件控制
    # 设置代理
    option.add_argument("--proxy-server=http://127.0.0.1:8080")
    driver = webdriver.Chrome(options=option)
    print('请使用第三方登录')
    driver = login.login(None, None, driver)
    # 跳入直播页面
    driver.get('https://fm.missevan.com/live/%s' %roomId)

    time.sleep(1)
    print('初始化机器人')
    robot1 = robot.robot(driver,db,unkey,key)

    print('机器人初始化完毕')
    time.sleep(4)
    # 获取cpu核心数量
    optimal_thread_count = multiprocessing.cpu_count()
    pool_scheduler = ThreadPoolScheduler(optimal_thread_count)
    # 观察join
    print('开启观察者，')
    rx.interval(0.3).pipe(
        ops.observe_on(pool_scheduler),
    ).subscribe(
        on_next=lambda i: process1(),
        on_error=lambda e: print('路由出错啦！', e),
        on_completed=lambda: print("PROCESS 3 done!"),
    )
    def process1():
        if not robot1.route():
            db2 = pickledb.load('ws.db', True)
            robot1.setDb(db2)
        else:
            print('??????')
    # rx.interval(1).pipe(
    #     ops.map(lambda i: i * 100),
    #     ops.observe_on(pool_scheduler),
    # ).subscribe(
    #     on_next=lambda i: print("PROCESS 4: {0} {1}".format('乌拉拉', i)),
    #     on_error=lambda e: print(e),
    # )
    # 程序退出时释放driver。

    input("Press any key to exit\n")
